package im.vinci.server.songbook.persistence;

import cn.jiguang.commom.utils.StringUtils;
import im.vinci.server.common.exceptions.VinciException;
import im.vinci.server.common.exceptions.error.ErrorCode;
import im.vinci.server.songbook.domain.PlayList;
import im.vinci.server.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mingjie on 16/12/6.
 */
@Repository
public class SongbookFileImpl implements SongbookMapper {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String DIRECTOEY = "src/main/resources/songbook/";

    private List<PlayList> data;

    @PostConstruct
    public void init() {
        data = doGetSongbookData();
        logger.info("Read songbook data files, size: {}", data.size());
    }

    private boolean checkValid(File sourceFile, PlayList playList) {
        boolean isValid = true;
        String fileName = sourceFile.getName().substring(0, sourceFile.getName().indexOf("."));
        if (StringUtils.isEmpty(playList.getPlayListName())) {
            logger.error("playListName is null or empty, fileName: {}", sourceFile.getName());
            isValid = false;
        }

        if (!fileName.equals(playList.getPlayListName())) {
            logger.error("文件与解析数据名不一致, fileName: {}, playListName: {}", fileName, playList.getPlayListName());
            isValid = false;
        }

        if (playList.getMusics() == null || playList.getMusics().isEmpty()) {
            logger.error("playlist 数据为空, fileName: {}", sourceFile.getName());
            isValid = false;
        }
        return isValid;
    }

    private List<PlayList> doGetSongbookData() {
        logger.info("Read songbook files once");

        List<PlayList> resultList = new ArrayList<>();

        File dir = new File(DIRECTOEY);

        if (!dir.exists() || !dir.isDirectory()) {
            logger.error("加载songbook数据失败, 资源目录不存在或不是目录, location: {}", DIRECTOEY);
            return resultList;
        }

        File[] files = dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (!name.endsWith(".json")) {
                    return false;
                }
                return true;
            }
        });

        for (File file : files) {
            try {
                PlayList playList = JsonUtils.getHttpObjectMapperInstance().readValue(file, PlayList.class);
                if (checkValid(file, playList)) {
                    resultList.add(playList);
                } else {
                    logger.error("解析songbook数据文件失败, 数据不对或格式不符, fileName: {}", file.getName());
                    break;
                }
            } catch (IOException e) {
                logger.error("读取文件出错, fileName: {}", file.getName(), e);
            }
        }

        if (files.length != resultList.size()) {
            logger.error("资源文件数和解析数据数目不一致, fileCount: {}, playListCount: {}", files.length, resultList.size());
            return new ArrayList<PlayList>();
        }

        return resultList;
    }

    @Override
    public List<PlayList> getSongbookData() {
        return data;
    }
}
